package com.itheima.reggie.service.Impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper,Category> implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Override
    public List<Category> findAll() {
        List<Category>  categoryList=categoryMapper.findAll();
        return categoryList;
    }

    @Override
    public void save1(Category category) {
        category.setId(IdUtil.getSnowflake(1,1).nextId());
//        category.setCreateTime(new Date());
//        category.setCreateUser(1L);
//        category.setUpdateTime(new Date());
//        category.setUpdateUser(1L);
        categoryMapper.save(category);
    }

    @Override
    public void update(Category category) {
//        category.setUpdateTime(new Date());
//        category.setUpdateUser(1L);
        categoryMapper.updateById(category);
    }

    @Override
    public ResultInfo deleteById(long id) {

        int count1 = categoryMapper.countDishByCategoryId(id);
        if (count1 > 0) {
            throw new CustomException("当前分类下存在菜品,不能删除");
//            return ResultInfo.error("当前分类下存在菜品,不能删除");
        }

        //2. 查看当前分类下是否有套餐,如果有,不允许删除本分类  查询setmeal表
        int count2 = categoryMapper.countSetmealByCategoryId(id);
        if (count2 > 0) {
            throw new CustomException("当前分类下存在菜品,不能删除");
        }

        //3. 当前分类下什么都没有,可以删除
        categoryMapper.deleteById(id);
        return ResultInfo.success(null);
    }
}
